package lucene_db;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;


public class Search {
	
	static String indexPath = "sindex";
	public static void Search(String keyword) throws IOException, ParseException
	{
		//搜索
        Directory dir=FSDirectory.open(new File(indexPath));
        Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_45);
        DirectoryReader directoryReader=DirectoryReader.open(dir);
        IndexSearcher indexSearcher=new IndexSearcher(directoryReader);
        
        QueryParser parser=new QueryParser(Version.LUCENE_45,"content", analyzer);
        
        //Query query=parser.parse(keyword);
        Query query=parser.parse(keyword);
        TopDocs topDocs=indexSearcher.search(query, null,100);
        ScoreDoc[] hits=topDocs.scoreDocs;
        //System.out.println(query.toString());
        System.out.println("查询结果数："+hits.length);
        
        for(int n=0;n<hits.length;n++)
        {
            Document hitDoc=indexSearcher.doc(hits[n].doc);
            System.out.println(n+1);
            System.out.println("title："+hitDoc.get("title"));
            System.out.println("content："+hitDoc.get("content"));
        }
	}
    

}

